package com.wechat.wechat.controller;

import com.lly835.bestpay.model.PayResponse;
import com.wechat.wechat.dto.OrderDTO;
import com.wechat.wechat.enums.ResultEnum;
import com.wechat.wechat.exception.SellException;
import com.wechat.wechat.service.OrderService;
import com.wechat.wechat.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * @author NN
 * @2020/2/25 18:59
 */
@Controller
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private PayService payService;

    @GetMapping("/create")
    public ModelAndView create(@RequestParam("orderId") String orderId,
                               @RequestParam("returnUrl") String returnUrl)
    {
        //1.查询订单
        OrderDTO orderDTO=orderService.findOne(orderId);
        if(orderDTO == null)
        {
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        //2.发起支付
        Map<String,Object> map=new HashMap<String,Object>();
        PayResponse payResponse = payService.create(orderDTO);
        map.put("payResponse",payResponse);
        map.put("returnUrl",returnUrl);

        //3.将预付款信息注入到模板文件中
        return  new ModelAndView("pay/create",map);
    }

    @PostMapping("/notify")
    public ModelAndView notify(@RequestBody String notifyData){
        payService.notify(notifyData);
        //返回给微信处理结果
        return new ModelAndView("pay/success");
    }


}
